package com.anrongtec.zcpt.manager;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.manager.APPDownloadManager.AppDownloadListener;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.module.Upgrade;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileUtils;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 商店  检测更新管理类
 *
 * @author cxy
 */
public class CheckNewVersionManager {

    private ProgressBar bar;
    private TextView tv_size, tv_total;
    private Context mContext;

    private static CheckNewVersionManager instance;

    public static synchronized CheckNewVersionManager getInstance() {
        if (instance == null) {
            instance = new CheckNewVersionManager();
        }
        return instance;
    }


    /**
     * 检查更新
     */
    public void checkVersion(final Context context, final boolean isShowToast) {
        String json = GsonUtil.toUpgradeJson(Util.getVersionCode(context));
//        LogUtil.e("检查更新" + json);
        HttpUtil.post(json, new StoreStringCallBack(context) {
            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                LogUtil.e(e.toString());
            }

            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
//                LogUtil.e("检查更新返回" + arg1);
                JsonDataRestult<Upgrade> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<Upgrade>>() {
                }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    final Upgrade data = result.getData();
                    final AppModel app = UpgradeToAppModel(data, context);
                    if (data.isUpdate()) {
                        String desc = "";
                        if (data.isForce()) {
                            desc = data.getExpVersion() + "(" + Util.byte2Mega(data.getExpSize()) + ")\n"
                                    + "版本描述:\n"
                                    + data.getVersionDesc()
                                    + "\n点击确定更新.";
                            //强制更新
                            DialogUtil.createAlertDialogSingel(context, "发现新版本", desc, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    checkDownload(app, context);
                                }
                            });
                        } else {
                            desc = data.getExpVersion() + "(" + Util.byte2Mega(data.getExpSize()) + ")\n"
                                    + "版本描述:\n"
                                    + data.getVersionDesc()
                                    + "\n\n是否立即更新？";

                            DialogUtil.createAlertDialog(context, "发现新版本", 0, desc, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    checkDownload(app, context);
                                }
                            });
                        }
                    } else if (isShowToast) {
                        ToastShow.shortMessage(context, "当前是最新版本，无需更新");
                    }
                } else {
//					ToastShow.shortMessage(result.getRetMsg());
                }
            }
        });
    }


    /**
     * 检测是否需要下载(已经下载完成的话则直接提示安装)
     *
     * @param app
     * @param context
     */
    private void checkDownload(AppModel app, Context context) {
        DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
        if (info == null || info.getState() != DownloadManager.FINISH) {
            download(app, context);
        } else {
            if (FileUtils.isExist(info.getTargetPath())) {
                ApkUtils.install(context, new File(info.getTargetPath()));
            } else {
                download(app, context);
            }
        }
    }


    /**
     * 下载 , 并显示dialog进度框
     *
     * @param app
     * @param context
     */
    private void download(AppModel app, Context context) {

        View v = LayoutInflater.from(context).inflate(R.layout.dialog_downloading_view, null);
        bar = (ProgressBar) v.findViewById(R.id.progress_dialog);
        tv_size = (TextView) v.findViewById(R.id.tv_dialog_current_size);
        tv_total = (TextView) v.findViewById(R.id.tv_dialog_total_size);
        tv_total.setText(Util.byte2Mega(app.getSize()));

        final Dialog dialog = DialogUtil.createViewDialog(context, "下载更新", 0, v, false, null, true, null);

        APPDownloadManager.addTaskNew(context, app, new AppDownloadListener() {
            @Override
            public void progress(DownloadInfo downloadInfo) {
                tv_size.setText(Util.byte2Mega(downloadInfo.getDownloadLength()));
                bar.setProgress((int) (downloadInfo.getProgress() * 100));
            }

            @Override
            public void finish(DownloadInfo downloadInfo) {
                dialog.cancel();
            }

            @Override
            public void error(DownloadInfo downloadInfo, String errorMsg, Exception e) {

            }
        });
    }


    /**
     * 转换为appmodel对象
     *
     * @param data
     * @return
     */
    private AppModel UpgradeToAppModel(Upgrade data, Context context) {
        AppModel app = new AppModel();
        app.setAppName("警务商店");
        app.setAppPackName(Util.getPackageName(context));
        app.setVersionDesc(data.getVersionDesc());
        app.setRemoteVersionCode(data.getExpVersionCode());
        app.setRemoteVersionName(data.getExpVersion());
        app.setSize(data.getExpSize());
        app.setUrl(data.getExpFileId());
        return app;
    }
}
